package com.onpositive.wiki3.db.impl;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import com.onpositive.compactdata.CompactLongVector;
import com.onpositive.wiki3.db.ITextContentAccess;
import com.onpositive.wiki3.db.IWikiDB;

public class TextContentAccess implements ITextContentAccess {

	protected IWikiDB db;
	protected RandomAccessFile fl;
	protected CompactLongVector positions;

	public TextContentAccess(File file, IWikiDB db) throws IOException {
		positions = new CompactLongVector(new File(file, "content.list"));
		fl = new RandomAccessFile(new File(file, "content.dat"), "r");
		this.db = db;
	}

	@Override
	public String getTextContent(int id) {
		try {
			if (id>=positions.size()){
				return "";
			}
			long i = positions.get(id);
			fl.seek(i);
			int readInt = fl.readInt();
			byte[] b = new byte[readInt];
			fl.readFully(b);
			return new String(b, "UTF-8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String getTextContent(String title) {
		int id = db.getTitleMapper().getId(title);
		if (id < 0) {
			return null;
		}
		return getTextContent(id);
	}

	@Override
	public boolean hasText(int id) {
		return id<positions.size();
	}

	@Override
	public int size() {
		return positions.size();
	}

}
